<template>
  <div class="mainList">
    <div class="searchMain">
      <div class="searchPos" :class="{'boxShow': searchHide}">
        <a-form ref="formSearchRef" :model="formSearch" v-if="columnsDistShow">
          <div class="form-main" :class="{'searchHide': searchHide}">
            <div class="form-item">
              <!-- <div class="searchTop-list tess">
                <a-select v-model="formSearch.keywords_type"
                      style="width:165px;"
                      :trigger-props='{trigger:"hover"}'
                      :bordered="false"
                      :options="keywordTypes"
                      default-value="keywords"
                      @change="(v)=>switchKeywordType(formSearch,v)">
                </a-select>
                <a-input v-model="formSearch[formSearch['keywords_type']??'keywords']" allow-clear placeholder="多个请用','割开"/>
              </div>
              <a-form-item :field="formSearch['keywords_type']" label="关键字" label-col-flex="90px" style="display: none;"></a-form-item> -->
              <a-form-item field="depot_id" label="仓库" :disabled="tableTabs" label-col-flex="90px" class="searchTop-list">
                <a-select v-model="formSearch.depot_id" :max-tag-count="1" :options="columnsDist.dicthelpApi_depot.data"
                          :field-names="{ value: 'id', label: 'name' }"
                          placeholder="请选择仓库" allow-clear allow-search :virtual-list-props="{height:200}">
                </a-select>
              </a-form-item>
              <a-form-item field="container_no" label="柜号" label-col-flex="90px" class="searchTop-list">
                <a-input v-model="formSearch.container_no" allow-clear placeholder="请输入柜号"/>
              </a-form-item>
              <a-form-item field="shipment_no" label="箱唛" label-col-flex="90px" class="searchTop-list">
                <a-input v-model="formSearch.shipment_no" allow-clear placeholder="请输入箱唛"/>
              </a-form-item>
              <a-form-item field="type" label="类型" label-col-flex="90px" class="searchTop-list">
                <a-select v-model="formSearch.type"
                          placeholder="请选择类型" allow-clear allow-search>
                  <a-option value="1">海运订单</a-option>
                  <a-option value="2">空运订单</a-option>
                  <a-option value="3">第三方转入</a-option>
                </a-select>
              </a-form-item>
              <a-form-item field="exportwith" label="清关类型" label-col-flex="90px" class="searchTop-list">
                <a-select v-model="formSearch.exportwith"
                          placeholder="请选择清关类型" allow-clear allow-search>
                  <a-option value="1">清关服务</a-option>
                  <a-option value="0">无需清关</a-option>
                </a-select>
              </a-form-item>
              <a-form-item field="frame" label="是否带车架" label-col-flex="90px" class="searchTop-list">
                <a-select v-model="formSearch.frame"
                          placeholder="请选择是否带车架" allow-clear allow-search>
                  <a-option value="1">是</a-option>
                  <a-option value="0">否</a-option>
                </a-select>
              </a-form-item>
              <a-form-item field="service_id" label="服务项目" label-col-flex="90px" class="searchTop-list">
                <a-select v-model="formSearch.service_id" :max-tag-count="1"
                          :options="columnsDist.dicthelpApi_waybillServiceTypeList.data"
                          :field-names="{ value: 'id', label: 'name' }"
                          placeholder="请选择服务" allow-clear allow-search :virtual-list-props="{height:200}">
                </a-select>
              </a-form-item>

              <a-form-item field="created_at" label="创建时间" label-col-flex="90px" class="searchTop-list">
                <a-range-picker
                    showTime
                    v-model="formSearch.created_at"
                    shortcuts-position="left"
                    :shortcuts="help.rangeShortcuts"
                    :time-picker-props="{
                        defaultValue:['00:00:00','23:59:59']
                        }"
                />
              </a-form-item>
            </div>
            <div class="form-buttom">
              <div>
                <a-button type="primary" html-type="submit" @click="submitSearch" style="margin-right: 10px;">
                  <template #icon>
                    <icon-search/>
                  </template>
                  搜索
                </a-button>
                <a-button @click="resetSearch">
                  <template #icon>
                    <icon-delete/>
                  </template>
                  重置
                </a-button>
              </div>
              <a-space class="lg:mt-0 mt-2"
                       style="margin-top: 20px;display: flex;justify-content: flex-end;margin-right: 10px">
                <a-tooltip content="显隐搜索">
                  <a-button shape="circle" @click="searchHide=!searchHide" style="margin-right: 10px">
                    <icon-search/>
                  </a-button>
                </a-tooltip>
                <a-tooltip content="设置">
                  <a-button shape="circle" @click="openSetting">
                    <icon-settings/>
                  </a-button>
                </a-tooltip>
              </a-space>
            </div>
          </div>

          <div class="touHide" style="display: flex;justify-content: center;margin-bottom: 10px;">
            <a-link v-if="searchHide" @click="searchHide=!searchHide" size="small">
              {{ searchHide ? '收起' : '' }}
              <template #icon>
                <icon-up v-if="searchHide"/>
              </template>
            </a-link>
          </div>
        </a-form>
      </div>
    </div>
    <div class="ma-content-block justify-between p-4 mainTable">
      <!-- 操作按钮 -->
      <div class="top-button">
        <div>
          <a-button type="primary" @click="addAction()">
            <template #icon>
              <icon-plus/>
            </template>
            新增
          </a-button>
        </div>
        <a-space class="lg:mt-0 mt-2">
          <a-tooltip content="显隐搜索">
            <a-button shape="circle" @click="searchHide=!searchHide">
              <icon-search/>
            </a-button>
          </a-tooltip>
          <a-tooltip content="设置">
            <a-button shape="circle" @click="openSetting">
              <icon-settings/>
            </a-button>
          </a-tooltip>
        </a-space>

      </div>
      <!-- tab切换 -->
      <a-tabs class="ma-tabs mb-1 tabs" @change="clickTap" v-if="!tableTabs" v-model:active-key="formSearch.status">
        <a-tab-pane :key="item.key" :title="item.title" v-for="item in shipmentTabs">
          <template #title>
            <slot :name="'tabTitle-' + item.label">{{ item.title }}{{ item.count ? `(${item.count})` : '' }}</slot>
          </template>
        </a-tab-pane>
      </a-tabs>
      <!-- 状态按钮 -->
      <div style="display: flex;">
        <button-group :button-groups="buttonGroups" :dataList="dataList" :crud-ref="crudRef" :selected="selected"
                      :currentStatus="currentStatus"/>
      </div>
      <div ref="tablePrantRef">
        <a-table ref="tableRef" :sticky-header="true" :scrollbar="true" :stripe="true"
                 :scroll="{ x: '100%', y: '100%' }" :columns="localColumns(columnsData,formSearch.status,'waybill')" :data="dataList"
                 class="table-list"
                 hide-expand-button-on-empty :loading="loading" row-key="id" v-model:selectedKeys="selected"
                 @selection-change="setSelecteds($event)" stripe :row-selection="rowSelection" column-resizable
                 :pagination="false">
          <!--  列表插槽    -->
          <template #customAgeTitle="{column}">
                  <div class="angle" @click="handleChange(column.dataIndex)">
                    <div v-if="column.dataIndex=='eta'">
                      <span>{{column.title}}</span>
                      <i class="angle_top" :class="{'angle_topTst':formSearch.orderType=='asc' && formSearch.orderBy=='eta'}"></i>
                      <i class="angle_bottom" :class="{'angle_bottomTst':formSearch.orderType=='desc' && formSearch.orderBy=='eta'}"></i>
                    </div>
                    <div v-else-if="column.dataIndex=='carry_at'">
                      <span>{{column.title}}</span>
                      <i class="angle_top" :class="{'angle_topTst':formSearch.orderType=='asc' && formSearch.orderBy=='carry_at'}"></i>
                      <i class="angle_bottom" :class="{'angle_bottomTst':formSearch.orderType=='desc' && formSearch.orderBy=='carry_at'}"></i>
                    </div>
                  </div>
                </template>
          <template #status="{ record }"
                    v-if="columnsDistShow">{{ getDictData('dictObj', 'waybill_sea_status', record.status, 2, columnsDist) }}
          </template>
          <template #type="{ record }" v-if="columnsDistShow">
            <div v-if="record.type==1">海运订单</div>
            <div v-else-if="record.type==2">空运订单</div>
            <div v-else-if="record.type==3">第三方转入</div>
          </template>
          <template #depot_id="{ record }"
                    v-if="columnsDistShow">{{ getDictData('attrApi', 'dicthelpApi_depot', record.depot_id, 3, columnsDist) }}
          </template>
          <template #service_id="{ record }"
                    v-if="columnsDistShow">{{ getDictData('attrApi', 'dicthelpApi_waybillServiceTypeList', record.service_id, 3, columnsDist) }}
          </template>
          <template #carrier="{ record }"
                    v-if="columnsDistShow">{{ getDictData('dictObj', 'waybill_carrier', record.carrier, 2, columnsDist) }}
          </template>
          <template #destination="{ record }"
                    v-if="columnsDistShow">{{ getDictData('attrApi', 'dicthelpApi_place', record.destination, 3, columnsDist) }}
          </template>

          <template #shipment_sum_parcel_count_estimate="{ record }">
            <template v-if="!record.shipment_sum_parcel_count_actual">
              {{record.shipment_sum_parcel_count_estimate}}
            </template>
            <template v-else-if="record.shipment_sum_parcel_count_actual == record.shipment_sum_parcel_count_estimate">
              {{record.shipment_sum_parcel_count_estimate}}
            </template>
            <span v-else class="text-red-500">
              {{ record.shipment_sum_parcel_count_actual || 0 }} / {{ record.shipment_sum_parcel_count_estimate }}
            </span>
          </template>
          <template #eta="{ record }">
            {{ record.eta.slice(0, 10) }}
          </template>
          <template #etd="{ record }">
            {{ record.etd.slice(0, 10) }}
          </template>
          <template #exportwith="{ record }">
            {{ record.exportwith == 1 ? '清关服务' : '无需清关' }}
          </template>
          <template #change_label="{ record }">
            {{ record.change_label == 1 ? '是' : '否' }}
          </template>
          <template #intercept_count="{ record }">
            {{ record.intercept_count == 1 ? '是' : '否' }}
          </template>
          <template #urgent="{ record }">
            {{ record.urgent == 1 ? '是' : '否' }}
          </template>
          <template #fixed="{ record }">
            <a-link title="接收托盘" @click="tray(record)">
              <icon-bookmark/>
            </a-link>
            <a-link title="编辑" @click="editAction(record)">
              <icon-edit/>
            </a-link>
            <a-link title="下载拆柜单" @click="downloadTap(record)">
              <icon-to-bottom/>
            </a-link>

            <!-- <a-popconfirm
                      content="确定要删除该数据吗?"
                      position="bottom"
                      @ok="deleteAction(record)"
                  >
                  <a-link title="删除"><icon-delete /></a-link>
            </a-popconfirm> -->
          </template>
        </a-table>
      </div>
      <!-- 分页 -->
      <div class="foot-list">
        <a-pagination
            :total="pageInfo.total"
            show-total show-jumper show-page-size
            v-model:current="formSearch.page"
            @change="pageChange"
            @page-size-change="pageSizeChange"
            :page-size-options="[10, 20, 30, 50, 100]"
            :page-size="formSearch.pageSize"
            style="display: inline-flex"
        />
      </div>
      <add-modal-form ref="addModalMormRef" @addClick="tableList" v-if="columnsDistShow"></add-modal-form>
      <tray-modal ref="trayModalRef" @addClick="tableList" v-if="columnsDistShow"></tray-modal>
      <setting ref="settingRef"></setting>
    </div>
  </div>

</template>
<script setup lang="jsx">
import {ref, reactive,provide,computed, watch, onMounted, h} from 'vue'
import waybill from '@/api/abroad/waybill'
import AddModalForm from "@/views/abroad/waybill/components/addModalForm.vue";
import trayModal from "@/views/abroad/waybill/components/trayMode.vue";
import {Message, Modal} from '@arco-design/web-vue'
import ButtonGroup from "@cps/actionsNew/buttonGroup.vue";
import tool from '@/utils/tool'
import help from '@/utils/help'
import {getDictData} from "@/utils/crud/dictNew.js";
import common from "@/api/common.js";
import dicthelpApi from "@/api/dicthelpApi.js";
import Setting from "@/views/components/setting.vue";
import {localColumns, tablePrantRefHeight} from "@/utils/crud/culmns.js";
import { useAppStore, useUserStore } from '@/store'
import { color } from 'echarts';
const crudRef = ref()
const addModalMormRef = ref()
const trayModalRef = ref()
const selected = ref([])
const columnsDistShow = ref(false)
const shipmentTabs = ref([])//tabs赋值
const countList = ref({})
const tableRef = ref()
const tablePrantRef = ref() //tabel 父级高度
const dataList = ref([])
const loading = ref(false)
const settingRef = ref()
const columnsDist = ref([])
const formSearchRef = ref(null)
const userStore = useUserStore()
//搜索更多是否显示
const searchHide = ref(false)
const currentStatus = computed(() => {
  let requestParams = formSearch
  if (!requestParams.status) {
    return null;
  }
  return requestParams.status
})
watch([shipmentTabs, countList],
    (newValues) => {
      if (shipmentTabs.value != '' && countList.value != '') {
        shipmentTabs.value.forEach(function (item) {
          item.count = countList.value[item.key] ? countList.value[item.key] : 0
        })
      }
    }
)

const columnsData = ref([
  {title: '状态', dataIndex: 'status', slotName: 'status', width: 100, align: 'center', hide: true,},
  {title: '订单类型', dataIndex: 'type', slotName: 'type', width: 70, align: 'center', hide: true,},
  {title: '转运仓', dataIndex: 'depot_id', slotName: 'depot_id', width: 60, align: 'center', hide: true,},
  {title: '提单号/入仓号', dataIndex: 'number', width: 180, align: 'center', hide: true,},
  {title: '柜号', dataIndex: 'container_no', width: 120, hide: true,},
  {title: '柜型', dataIndex: 'container_type', width: 45, hide: true,},
  {title: '服务项目', dataIndex: 'service_id', slotName: 'service_id', width: 120, align: 'center', hide: true,},
  {title: '清关', dataIndex: 'exportwith', slotName: 'exportwith', width: 100, align: 'center', hide: true,},
  {
    title: '总件数',
    dataIndex: 'shipment_sum_parcel_count_estimate',
    slotName: 'shipment_sum_parcel_count_estimate',
    width: 70,
    align: 'center',
    hide: true,
  },
  {title: '承运商', dataIndex: 'carrier', slotName: 'carrier', align: 'center', width: 80, hide: true,ellipsis:true},
  {title: '目的港', dataIndex: 'destination', slotName: 'destination', align: 'center', width: 100, hide: true,},
  {title: 'ETD', dataIndex: 'etd', slotName: 'etd', width: 90, align: 'center', hide: true,},
  {title: 'ETA/入仓', dataIndex: 'eta', slotName: 'eta', width: 90, align: 'center', hide: true, titleSlotName: 'customAgeTitle',},
  {title: '提柜日期', dataIndex: 'carry_at', width: 150, align: 'center', hide: true,titleSlotName: 'customAgeTitle',},
  {title: '创建日期', dataIndex: 'created_at', width: 150, align: 'center', hide: true,ellipsis:true,},
  {title: '换标', dataIndex: 'change_label', slotName: 'change_label', width: 40, align: 'center', hide: true,},
  {
    title: '拦截',
    dataIndex: 'intercept_count',
    slotName: 'intercept_count',
    align: 'center',
    width: 40,
    hide: true,
  },
  {title: '加急', dataIndex: 'urgent', slotName: 'urgent', align: 'center', width: 40, hide: true,},
  {title: '备注', dataIndex: 'remark', width: 100,align: 'center',hide: true,},
  {title: '描述', dataIndex: 'describe',width: 100,align: 'center', hide: true,},
  {title: '操作', slotName: 'fixed', fixed: 'right', width: 100, align: 'center', hide: true,},

]);
const tableTabs=ref(false)
const open = async (address_id,type_status) => {
  tableTabs.value=true
  formSearchRef.value.resetFields();
  formSearch.page=1
  formSearch.status=type_status
  tableList()
}

const openSetting = () => {
  settingRef.value.open()
}
//新增
const addAction = () => {
  addModalMormRef.value.onShow()
}
//接收托盘
const tray = (record) => {
  trayModalRef.value.onShow(record)
}
//详情
const editAction = (record) => {
  addModalMormRef.value.onShow(record)
}
//下载
const downloadTap = (record) => {
  // addModalMormRef.value.onShow(record)
  waybill.CabinetRemovalList({id: record.id}).then(res => {
    tool.download(res)
    Message.success('请求成功，文件开始下载')
  })
}
//删除数据
const deleteAction = async record => {
  const response = await waybill.deletes({ids: [record.id]})
  response.success && Message.success(response.message || `删除成功！`)
  tableList()
}
//总页数
const pageInfo = ref({
  currentPage: 1,
  total: 0,
  totalPage: 1
})
//table 选择
const rowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true,
  checkStrictly: true
});
//列表请求数据
const formSearch = reactive({
  depot_id: '',
  address_id:'',
  type: '',
  exportwith: '',
  frame: '',
  container_no: '',
  orderBy:'eta',
  orderType:'desc',
  service_id: '',
  shipment_no:'',
  created_at: [],
  refresh_tabs: 1,
  keywords_type: 'keywords',
  page: 1,
  pageSize: 10,
  status: '',
})
//重置
const resetSearch = (e) => {
  formSearchRef.value.resetFields();
  console.log('formSearch', formSearch)
  tableList()
}
//搜索
const submitSearch = (e) => {
  formSearch.page = 1
  formSearch.refresh_tabs = 1
  searchHide.value = false
  tableList()
}
//切换分页
const pageChange = (e) => {
  if (e) {
    formSearch.page = e
    tableList()
  }
}
//切换条数
const pageSizeChange = (e) => {
  if (e) {
    tool.local.set('pageSize', e)
    formSearch.pageSize = e
    tableList()
  }
}
//行数选中
const setSelecteds = (key) => {
  selected.value = key
}
//tabs切换
const clickTap = (e) => {
  formSearch.page = 1
  formSearch.status = e
  formSearch.refresh_tabs = 0
  tableList()
}
//排序
const handleChange = (dataIndex) => {
    formSearch.orderBy=dataIndex
  formSearch.orderType=formSearch.orderType=='desc' ? 'asc':'desc'
  tableList()
}

//列表
const tableList = () => {
  loading.value = true
  if(tableTabs.value){
    formSearch.refresh_tabs=0
    formSearch.is_intercept=0
    formSearch.depot_id=userStore.currentDepot.id
    formSearch.orderBy='eta'
    formSearch.orderType='asc'
  }
  formSearch.pageSize=tool.local.get('pageSize') || 10
  waybill.getList(formSearch).then(res => {
    dataList.value = res.data.items
    //页数
    pageInfo.value = res.data.pageInfo
    countList.value = res.data.count
    formSearch.status = res.data.current_type.toString()
    selected.value = []
    loading.value = false
    tablePrantRefHeight(tablePrantRef.value)
  })
}

onMounted(() => {
  tableList()
})

const keywordTypes = [
  //  转单号   供应商单号
  {value: 'keywords', label: '单号'},
  // {value: 'public_number', label: '系统提单号'},
  {value: 'shipment_no', label: '运单号'},
  {value: 'outer_carrier_tracking_number', label: '转单号', index: '快递单号'},
  {value: 'ext_number', label: '扩展单号'},
  // {value: 'number', label: '客户单号'},
]
const switchKeywordType = (form, value) => {
  keywordTypes.map(i => {
    if (form[i.value] && i.value !== value) {
      form[value] = form[i.value]
      form[i.value] = undefined
    }
  })
}
//字典
const waybillColumns = async () => {
  let attrDict = ['containerType', 'waybill_sea_status', 'countrys','AttachmentType','waybill_carrier']
  let [dictObj, dicthelpApi_depot, dicthelpApi_supplier, dicthelpApi_waybillServiceTypeList, dicthelpApi_place] = await Promise.all([
    common.getDicts(attrDict), dicthelpApi.depot({sea: 1}),
    dicthelpApi.supplier({type: ['5']}), dicthelpApi.waybillServiceTypeList(), dicthelpApi.place()
  ])
  return reactive({
    dictObj,
    dicthelpApi_depot,
    dicthelpApi_supplier,
    dicthelpApi_waybillServiceTypeList,
    dicthelpApi_place,
  })
}

waybillColumns().then(res => {
  console.log('jjjjjjjjjjjj', res)
  columnsDist.value = res
  columnsDistShow.value = true
  let parcelType = res.dictObj.data.waybill_sea_status
  if (parcelType) {
    let obj = {
      id: '',
      title: '全部',
      key: '',
    }
    parcelType.push(obj)
    shipmentTabs.value = parcelType
  }
})
const buttonGroups = [
  {
    title: '通过',
    api: waybill.pass,
    auth: ['sea:waybill:pass'],
    hideStatus: [2, 3, 4, 5, 6, 7, 8, 9, null]
  },
  {
    title: '拒绝',
    api: waybill.reject,
    status: 'danger',
    auth: ['sea:waybill:reject'],
    hideStatus: [2, 3, 4, 5, 6, 7, 8, 9, null]
  },
  {
    title: '待结算',
    api: waybill.pendingSettlement,
    auth: ['sea:waybill:pendingSettlement'],
    hideStatus: [1, 2, 3, 4, 5, 6, 8, 9, null]

  },
  {
    title: '结算',
    api: waybill.settlement,
    auth: ['sea:waybill:settlement'],
    hideStatus: [1, 2, 3, 4, 5, 6, 7, 9, null]

  },
  {
    title: '准备提柜',
    api: waybill.prepareCarry,
    auth: ['sea:waybill:prepareCarry'],
    hideStatus: [1,2, 4, 5, 6, 7, 8, 9, null],
    form: {
          columns: [
            {
              title: '提柜日期', dataIndex: 'time',formType: "date", showTime: true,
              rules: {required: true, message: "请选择提柜日期"},
            }
          ]
        }
  },
  {
    title: '提柜',
    api: waybill.carry,
    auth: ['sea:waybill:carry'],
    hideStatus: [1,2, 3, 5, 6, 7, 8, 9, null],
   
  }
  // {
  //   title: '作废',
  //   api: waybillTask.void,
  //   status: 'danger',
  //   auth: ['sea:waybillTask:void'],
  //   hideStatus: [2, 3, 4, 5, 6, 7,8,9, null]

  // },
]

provide('tableList', tableList);
provide('getDictData', getDictData)
provide('columnsData', columnsData)
provide('columnsDist', columnsDist)//全部字典
provide('dataList', dataList)
provide('formSearch', formSearch)
provide('selected', selected)
defineExpose({ open })

</script>
<script lang="jsx"> export default {name: 'sea:waybill'} </script>
<style>
.form-inline-card > .arco-card-body {
  padding: 0;
  display: grid;
  grid: 1fr / 1fr 1fr 1fr;
}

.form-inline-card > .arco-card-header {
  display: none;
}

.fee-up {
  border-bottom: dashed #777777 1px;
}

.fee-down {
  color: orange;
}

.customer-input-item .arco-btn-group button:first-child {
  display: none;
}

.table-list {
  margin-top: 5px;
}

.arco-tabs-content {
  padding: 0;
}

.foot-list {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.mainTable {
  padding-top: 68px;
}

.arco-select-view-inner {
  white-space: nowrap;
}

.arco-select-view-inner .arco-tag {
  white-space: nowrap !important;
}

.tabs .arco-tabs-tab {
  min-width: 70px;
  justify-content: center;
}
.angle{
  cursor:pointer;
}
.angle_top {
      content: '';
      width: 0;
      height: 0;
      display: block;
      border-style: solid;
      border-width: 0 5px 5px;
      border-color: transparent transparent #5e5e5e;
      position: absolute;
      transform: rotate(180deg);
      bottom: 10px;
      right: 2px;
    }
    .angle_topTst{
      border-color: transparent transparent rgb(41, 38, 241);

    }
    .angle_bottom { 
      content: '';
      width: 0;
      height: 0;
      display: block;
      border-style: solid;
      border-width: 0 5px 5px;
      border-color: transparent transparent #5e5e5e;
      position: absolute;
      top: 10px;
      right: 2px;
    }
    .angle_bottomTst{
      border-color: transparent transparent rgb(41, 38, 241);

    }
</style>